package com.dunqi.gpm.cangxi.home.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import com.dunqi.gpm.cangxi.R;
import com.dunqi.gpm.cangxi.common.api.ApiFactory;
import com.dunqi.gpm.cangxi.common.api.RxSchedulers;
import com.dunqi.gpm.cangxi.common.base.BaseAct;
import com.dunqi.gpm.cangxi.common.base.ComObserver;
import com.dunqi.gpm.cangxi.common.base.Data;
import com.dunqi.gpm.cangxi.common.util.Arith;
import com.dunqi.gpm.cangxi.common.util.JsonUtils;
import com.dunqi.gpm.cangxi.common.util.TimeUtil;
import com.dunqi.gpm.cangxi.common.view.ComTitleBar;
import com.dunqi.gpm.cangxi.common.view.NoScrollGridView;
import com.dunqi.gpm.cangxi.home.adapter.PhotoAdapter;
import com.dunqi.gpm.cangxi.home.bean.Pic;
import com.dunqi.gpm.cangxi.home.bean.ProjectTimeline;
import com.dunqi.gpm.cangxi.home.constance.Constance;
import com.dunqi.gpm.cangxi.home.fragment.HomeFragment;
import com.dunqi.gpm.cangxi.home.widget.NormalView;
import com.dunqi.gpm.cangxi.mine.util.UserUtil;
import com.foamtrace.photopicker.intent.PhotoPreviewIntent;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

/**
 * Created by 空 on 2017/11/27 0027.
 */

public class ProjectProgressDetailsActivity extends BaseAct implements AdapterView.OnItemClickListener {
    private static final String DATA = "list_photo";
    @BindView(R.id.title_bar)
    ComTitleBar titleBar;
    @BindView(R.id.start_audit_tv)
    TextView startAuditTv;
    @BindView(R.id.is_audit_view)
    NormalView isAuditView;
    @BindView(R.id.audit_idea_view)
    NormalView auditIdeaView;
    @BindView(R.id.report_time_view)
    NormalView reportTimeView;
    @BindView(R.id.progress_type_view)
    NormalView progressTypeView;
    @BindView(R.id.report_period_view)
    NormalView reportPeriodView;
    @BindView(R.id.report_end_time_view)
    NormalView reportEndTimeView;
    @BindView(R.id.progress_generate_time_view)
    NormalView progressGenerateTimeView;
    @BindView(R.id.is_settlement_view)
    NormalView isSettlementView;
    @BindView(R.id.this_plan_money_view)
    NormalView thisPlanMoneyView;
    @BindView(R.id.this_complet_money_view)
    NormalView thisCompletMoneyView;
    @BindView(R.id.this_percent_view)
    NormalView thisPercentView;
    @BindView(R.id.year_percent_view)
    NormalView yearPercentView;
    @BindView(R.id.actual_start_time_view)
    NormalView actualStartTimeView;
    @BindView(R.id.actual_end_time_view)
    NormalView actualEndTimeView;
    @BindView(R.id.progress_happening_view)
    NormalView progressHappeningView;
    @BindView(R.id.next_work_plan_view)
    NormalView nextWorkPlanView;
    @BindView(R.id.next_plan_money_view)
    NormalView nextPlanMoneyView;
    @BindView(R.id.grid_view)
    NoScrollGridView gridView;
    @BindView(R.id.mark_view)
    NormalView markView;
    @BindView(R.id.edit_tv)
    TextView editTv;
    @BindView(R.id.container)
    View container;

    private long pro_plan_progress_id;

    int[] auditColors = new int[3];
    String[] audits = {"待审核", "通过", "未通过"};
    String[] progressDes = {"进展顺利", "基本正常", "进度滞后", "申请结项"};
    private ProjectTimeline item;
    private ArrayList<String> paths;

    int[] progressColors = new int[5];

    @Override
    protected void refreshData(Bundle savedInstanceState) {
        net();
    }

    private void net() {
        ApiFactory.getInstance()
                .getProjectProgressDetailInfo(pro_plan_progress_id)
                .compose(RxSchedulers.<Data<ProjectTimeline>>io_main())
                .subscribe(new ComObserver<ProjectTimeline>() {
                    @Override
                    public void onSuccess(ProjectTimeline projectTimeline) {
                        item = projectTimeline;
                        refreshUi();
                    }

                    @Override
                    public void onFinal() {

                    }

                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposables(d);
                    }
                });
    }

    private void refreshUi() {
        progressColors[0] = R.color.color_0099cc;
        progressColors[1] = R.color.color_0099cc;
        progressColors[2] = R.color.color_cc9900;
        progressColors[3] = R.color.color_669900;
        progressColors[4] = R.color.color_cc6600;

        int status = item.getAuditStatus();

        if (status - 1 >= 0) {
            isAuditView.setText(audits[status - 1]);
            isAuditView.setTextColor(auditColors[status - 1]);
            reportTimeView.setText(item.getReportTime());
        }
        auditIdeaView.setText(item.getAuditRemark());
        int progressType = item.getProgressType();
        if (progressType - 1 >= 0) {
            progressTypeView.setTextColor(progressColors[progressType]);
            progressTypeView.setText(progressDes[progressType - 1]);
        }

        String reportTypeTxt = item.getReportType() == 1 ? "日报" : "定期汇报";
        reportPeriodView.setText(TimeUtil.getTen(item.getReportPeriod()) + "(" + reportTypeTxt + ")");
        reportEndTimeView.setText(item.getEndReportDate());
        progressGenerateTimeView.setText(item.getGenerateTime());
        isSettlementView.setText(item.getApplySettlement() == 1 ? "是" : "否");

        thisPlanMoneyView.setText(String.valueOf(item.getCurrentPeriodInvestiment()));
        thisCompletMoneyView.setText(String.valueOf(item.getCurrentPeriodInvested()));
        if (item.getCurrentPeriodInvestiment() != 0) {
            double div = Arith.div(item.getCurrentPeriodInvested() * 100, item.getCurrentPeriodInvestiment(), 2);
            thisPercentView.setText(div + "%");
        }

        String actualStartTime = item.getActualStartTime();
        if (actualStartTime == null) {
            actualStartTime = "";
        }
        actualStartTimeView.setText(actualStartTime);
        String actualCompleteTime = item.getActualCompleteTime();
        if (actualCompleteTime == null) {
            actualCompleteTime = "";
        }
        actualEndTimeView.setText(actualCompleteTime);

        progressHappeningView.setText(item.getProgressDesc());
        markView.setText(item.getRemark());

        String picRemarkRecords = item.getPicRemarkRecords();
        if (TextUtils.isEmpty(picRemarkRecords)) {

        } else {
            ArrayList<Pic> pics = JsonUtils.fromJson(picRemarkRecords, new TypeToken<ArrayList<Pic>>() {
            }.getType());
            paths = new ArrayList<>();
            for (Pic pic : pics) {
                paths.add(UserUtil.getBaseUrl() + pic.getUrl());
            }
            gridView.setAdapter(new PhotoAdapter(getActivity(), paths));
            gridView.setOnItemClickListener(this);
        }

        int levelType = UserUtil.getLevelType();
        if (UserUtil.userFromNdrcOrg()) {
            if (status == 1) {
                startAuditTv.setVisibility(View.VISIBLE);
            } else {
                startAuditTv.setVisibility(View.GONE);
            }
        }

        if (HomeFragment.homeMenuId == 1 && UserUtil.userFromRespOrg() && (status <= 0 || status == 3)) {
            //填写
            editTv.setVisibility(View.VISIBLE);
            editTv.setOnClickListener(v -> {
                if (item == null) {
                    return;
                }
                UpdateProgressActivity.start(getActivity(), item.getProjectId(), 0,
                        item.getAuditStatus(), item.getReportPeriod(), item.getProAnnualPlanId()
                        , item.getProPlanProgressId(), item.getPlanYear());
            });
        }
    }

    @Override
    protected void initUiAndListener() {
        auditColors[0] = R.color.text_color_select_gray;
        auditColors[1] = R.color.text_color_normal_green;
        auditColors[2] = R.color.red;

        progressColors[0] = R.color.color_00b32d;
        progressColors[1] = R.color.color_0066cc;
        progressColors[2] = R.color.color_ff0000;
        progressColors[3] = R.color.color_b3000000;

        pro_plan_progress_id = getIntent().getLongExtra(DATA, 0);

        if (HomeFragment.homeMenuId == 2) {
            container.setVisibility(View.GONE);
            titleBar.setTitle("每日进展详情");
        } else {
            container.setVisibility(View.VISIBLE);
        }

//        int homeMenuId = UserUtil.getLevelType();
//        if (homeMenuId == 2) {
//            startAuditTv.setVisibility(View.VISIBLE);
//        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_project_progress_detail;
    }

    public static void start(Activity context, long pro_plan_progress_id) {
        Intent intent = new Intent(context, ProjectProgressDetailsActivity.class);
        intent.putExtra(DATA, pro_plan_progress_id);
        context.startActivityForResult(intent, 54);
    }


    @OnClick({R.id.is_audit_view_click, R.id.start_audit_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.is_audit_view_click:
                //项目审批详情

                break;
            case R.id.start_audit_tv:
                //立即开始审核
                if (item == null) {
                    return;
                }
                long proPlanProgressId = item.getProPlanProgressId();
                int reportType = item.getReportType();
                WarningAuditActivity.start(getActivity(), String.valueOf(proPlanProgressId), item.getProjectName(), reportType);
                break;
            default:
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (item == null) {
            return;
        }
        //WarningAuditActivity
//        if (resultCode == 200) {
//            item.setAuditStatus(2);
//        }
//
//        if (resultCode == 400) {
//            item.setAuditStatus(3);
//        }

//        UpdateProgressActivity WarningAuditActivity
        if (resultCode == UpdateProgressActivity.RESULT_CODE) {
            setResult(resultCode);
        }

        if (resultCode == WarningAuditActivity.RESULT_CODE) {
            setResult(resultCode);
        }

        finish();


//        refreshUi();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        PhotoPreviewIntent intent = new PhotoPreviewIntent(getActivity());
        intent.setCurrentItem(position); // 当前选中照片的下标
        intent.setPhotoPaths(paths); // 已选中的照片地址
        startActivityForResult(intent, Constance.REQUEST_PREVIEW_CODE);
    }
}
